﻿using System;
using System.Windows.Forms;
using ConfigurationManagement.Administration.UI.Utilities;
using ConfigurationManagement.Data;
using ConfigurationManagement.MsBuild;

namespace ConfigurationManagement.Administration.UI.Import
{
    public partial class ExportXmlDictionaryForm : Form
    {
        private readonly ConfigurationManagementDataContext _db = new ConfigurationManagementDataContext();
        private Project _selectedProject;
        private Solution _selectedSolution;

        public ExportXmlDictionaryForm()
        {
            InitializeComponent();
        }

        private void BrowseButtonClick(object sender, EventArgs e)
        {
            var dr = saveFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                DictionaryPathTextBox.Text = saveFileDialog1.FileName;
            }
        }

        private void ImportXmlDictionaryFormLoad(object sender, EventArgs e)
        {
            LoadProjects();
        }

        private void LoadProjects()
        {
            ProjectsComboBox.DisplayMember = "ProjectName";
            ProjectsComboBox.ValueMember = "ProjectID";
            ProjectsComboBox.DataSource = _db.Projects;
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void LoadSolutions()
        {
            if (_selectedProject == null) return;
            SolutionsComboBox.DisplayMember = "SolutionName";
            SolutionsComboBox.ValueMember = "SolutionID";
            SolutionsComboBox.DataSource = _selectedProject.Solutions;
            _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
        }

        private void ProjectsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProjectsComboBox.SelectedIndex < 0) return;
            _selectedProject = (Project) ProjectsComboBox.SelectedItem;
            LoadSolutions();
        }

        private void ImportButtonClick(object sender, EventArgs e)
        {
            var task = new ExportDictionary
                           {
                               ProjectName = _selectedProject.ProjectName,
                               SolutionName = _selectedSolution.SolutionName,
                               OutputPath = DictionaryPathTextBox.Text,
                               HostObject = new TaskHost(),
                               BuildEngine = new BuildEngine()
                           };
            task.Execute();
            MessageBox.Show(@"The data has been exported successfully");
        }

        private void SolutionsComboBoxSelectedIndexChanged(object sender, EventArgs e)
        {
            if (SolutionsComboBox.SelectedIndex >= 0)
            {
                _selectedSolution = (Solution) SolutionsComboBox.SelectedItem;
            }
        }
    }
}